import 'package:dotted_border/dotted_border.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:geomancy/api/geomancy.dart';
import 'package:geomancy/enums/index.dart';
import 'package:geomancy/mock/health_data.dart';
import 'package:geomancy/providers/user_provider.dart';
import 'package:geomancy/styles/index.dart';
import 'package:geomancy/tools/constant.dart';
import 'package:geomancy/tools/utils.dart';
import 'package:geomancy/widgets/common_btn.dart';
import 'package:geomancy/widgets/common_header.dart';
import 'package:geomancy/widgets/common_text.dart';
import 'package:geomancy/widgets/common_title.dart';
import 'package:geomancy/widgets/date_picker/index.dart';
import 'package:geomancy/widgets/modal_util/index.dart';
import 'package:geomancy/widgets/stroke_text.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

class HealthIndexPage extends StatefulWidget {
  const HealthIndexPage({super.key});

  @override
  State<HealthIndexPage> createState() => _HealthIndexPageState();
}

class _HealthIndexPageState extends State<HealthIndexPage> {
  ///康养所需生日
  String? birthday;
  ///康养所需性别
  String? sex;
  ///宜居方位
  String? station;
  ///命理信息
  String? info;
  ///方位index
  int? stationIndex;

  @override
  void initState() {
    super.initState();
    final user = context.read<UserProvider>().getUserInfo;
    birthday = user?.birthday?.split(' ')[0];
    sex = user?.sex;
    getLastRecordDetail();
  }

  ///获取最近一条康养记录
  Future getLastRecordDetail() async {
    final result = await GeomancyAPI.getLastRecordDetail(context, CompassSource.health);
    if (result != null && result.birthday != null) {
      final String birthday = result.birthday!;
      final year = DateTime.parse(birthday).year;
      final int index = computeResult(year);
      final sexStr = result.sex == '1' ? 'male' : 'female';
      final s = HealthData.gridData[sexStr][index.toString()]['station'];
      final m = HealthData.gridData[sexStr][index.toString()]['mingli'];
      final i = HealthData.gridData[sexStr][index.toString()]['index'];
      setState(() {
        stationIndex = i;
        station = s;
        info = m;
      });
    }
  }

  int computeResult(int value) {
    int total = value;
    while (total >= 10) {
      total = total.toString().split('').map((e) => int.parse(e)).reduce((a, b) => a + b);
    }
    return total;
  }

  ///出生年月弹窗
  void showBirthdayModal() {
    DatePickerUtil.show(context,
      height: 570.w,
      defaultValue: birthday,
      header: Container(
        height: 100.w,
        alignment: Alignment.center,
        child: const CommonText(txt: '设置出生年月', weight: FontWeight.bold),
      ),
      getValue: (String value) {
        birthday = value;
        showSexModal();
      }
    );
  }
  ///性别弹窗
  void showSexModal() {
    ModalUtil.showBottomModal(
      context: context,
      child: (state) => Material(
        color: ColorStyle.themeLightColor,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(60.w),
          topRight: Radius.circular(60.w),
        ),
        child: SafeArea(
          child: Container(
            width: double.infinity,
            height: 570.w,
            padding: EdgeInsets.fromLTRB(120.w, 0, 120.w, 20.w),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Container(
                  height: 100.w,
                  alignment: Alignment.center,
                  child: const CommonText(txt: '设置性别', weight: FontWeight.bold),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Column(
                      children: [
                        GestureDetector(
                          onTap: () {
                            Utils.shake();
                            state(() {
                              sex = '0';
                            });
                          },
                          child: Container(
                              margin: EdgeInsets.only(bottom: 14.w),
                              width: 220.w,
                              height: 220.w,
                              decoration: BoxDecoration(
                                  borderRadius: BorderRadius.all(Radius.circular(110.w))
                              ),
                              child: DottedBorder(
                                borderType: BorderType.RRect,
                                strokeWidth: 5.w,
                                radius: Radius.circular(110.w),
                                dashPattern: [12.w, 6.w],
                                color: sex == '0' ? ColorStyle.borderColor : Colors.transparent,
                                padding: EdgeInsets.all(1.w),
                                child: Image.asset('assets/icons/register_sex_avatar_female.png', width: 220.w, fit: BoxFit.cover),
                              )
                          ),
                        ),
                        Image.asset('assets/icons/register_sex_icon_female.png', width: 56.w),
                      ],
                    ),
                    Column(
                      children: [
                        GestureDetector(
                          onTap: () {
                            Utils.shake();
                            state(() {
                              sex = '1';
                            });
                          },
                          child: Container(
                            margin: EdgeInsets.only(bottom: 14.w),
                            width: 220.w,
                            height: 220.w,
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.all(Radius.circular(110.w))
                            ),
                            child: DottedBorder(
                              borderType: BorderType.RRect,
                              strokeWidth: 5.w,
                              radius: Radius.circular(110.w),
                              dashPattern: [12.w, 6.w],
                              color: sex == '1' ? ColorStyle.borderColor : Colors.transparent,
                              padding: EdgeInsets.all(1.w),
                              child: Image.asset('assets/icons/register_sex_avatar_male.png', width: 220.w, fit: BoxFit.cover),
                            ),
                          ),
                        ),
                        Image.asset('assets/icons/register_sex_icon_male.png', width: 56.w),
                      ],
                    )
                  ],
                ),
                CommonBtnWidget(txt: '下一步', size: Size(590.w, 80.w), onTap: nextHandle)
              ],
            ),
          ),
        ),
      )
    );
  }

  ///安康位next
  void nextHandle() {
    if (sex == null) {
      EasyLoading.showToast('请选择性别');
      return;
    }
    context.push('/health_position_tips', extra: {
      "birthday": birthday,
      "sex": sex
    });
  }

  void onTap() {
    Utils.shake();
    showBirthdayModal();
  }



  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CommonHeader.appBar(context: context),
      backgroundColor: ColorStyle.pageDefaultColor,
      body: ListView(
        physics: const ClampingScrollPhysics(),
        padding: EdgeInsets.fromLTRB(Constant.PAGEPADDING.w, 20.w, Constant.PAGEPADDING.w, Constant.PAGEPADDING.w),
        children: [
          const CommonTitleWidget(txt: '安康位'),
          Container(
            margin: EdgeInsets.only(top: 20.w),
            padding: EdgeInsets.only(top: 66.w, left: 40.w, right: 40.w, bottom: 60.w),
            decoration: BoxDecoration(
              color: ColorStyle.themeLightColor,
              border: Border.all(width: 5.w, color: ColorStyle.borderColor),
              borderRadius: BorderRadius.all(Radius.circular(60.w))
            ),
            child: Column(
              children: [
                if (stationIndex == null)
                  Image.asset('assets/icons/compass.png', width: 300.w, height: 300.w)
                else
                  Image.asset('assets/grid/health_compass_station_$stationIndex.png', width: 300.w, height: 300.w),
                Container(
                  height: 60.w,
                  margin: EdgeInsets.only(top: 60.w),
                  child: Row(
                    children: [
                      Container(
                        margin: EdgeInsets.only(top: station != null ? 5.w : 0),
                        width: 180.w,
                        child: const CommonText(txt: '宜居方位：', weight: FontWeight.bold),
                      ),
                      StrokeText(txt: station??'***', fontSize: 40.sp, fontFamily: 'fontHanSerifCN'),
                    ],
                  ),
                ),
                Container(
                  height: 60.w,
                  margin: EdgeInsets.only(top: 10.w),
                  child: Row(
                    children: [
                      Container(
                        margin: EdgeInsets.only(top: info != null ? 5.w : 0),
                        width: 180.w,
                        child: const CommonText(txt: '个人命理：', weight: FontWeight.bold),
                      ),
                      CommonText(txt: info??'***', weight: FontWeight.bold),
                    ],
                  ),
                ),
                Container(
                  margin: EdgeInsets.symmetric(vertical: 40.w),
                  child: CommonBtnWidget(txt: '开始', onTap: onTap),
                ),
                const CommonText(txt: '“安康位”即最有利于自己身体健康的居住方位，结合屋宅的坐向朝向，依据个人命理信息得出，是对于一套屋宅来说一个人一生永不改变的方位。'),
              ],
            ),
          ),
        ],
      )
    );
  }
}
